/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ChatNI;

import MVC.ChatController;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ListenTCP
 * Class in charge of listening to the chosen TCP port
 * This class inherits a thread
 * @author Duy Duc ,Metangmo
 */
public class ListenTCP extends Thread{
    
    private ChatController controller;
    private Socket socket;
    private ServerSocket server;
    private int port;

    /**
     * Constructor
     * @param controller
     *        Instance of the ChatController
     * @param port
     *        Chosen TCP port for a file transfer
     * @param fic
     *        Pointer to the transfered file
     */
    public ListenTCP(ChatController controller, int port, File fic) {
        this.controller = controller;
        this.port = port;
    }

   
    /**
     * run:
     * thread in charge of perpetual listening to the chosen TCP port
     * After a file transfer, it starts waiting again
     */
    public void run() {
        
        if (socket == null) {
            try {
                //Create a new socket corresponding with a specific port
                server = new ServerSocket(port);

            } catch (IOException ex) {
                System.out.println("Error with the TCP server, " + ex.getMessage());
            }
        }
        
        while (true) {
            try {
                
                System.out.println ( "Server TCP is in mode Listen  ");
                //Connection is accepted 
                socket = server.accept();
                System.out.println("Accepted connection  : " + socket );
                
                // Receipt of the file
                this.receiveFile();

            } catch (Exception e) {
                System.err.println("Error in connection attempt!!!!!!");
            }
        }
    }

 
    /**
     * receiveFile:
     * function collects the transfered file and stores it at the desired point by the user
     */
    public void receiveFile() {
        try {
            int bytesRead;

            DataInputStream clientData = new DataInputStream(socket.getInputStream());
            String fileName = clientData.readUTF();
            
            OutputStream output = new FileOutputStream((controller.getDirectoryToStore()+"/" + fileName));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }

            output.close();
            clientData.close();
            controller.performReceiveNotification(" FILE   "+fileName+"  SUCCESFULLY RECEIVED  ! \n ");
        } catch (IOException ex) {
            System.err.println("Client error!!! Connection is closed!!!");
        }
    }
    
}
    
    
    
    
